package com.wx.service.impl;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;

import com.base.util.BeanToMapUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wx.service.WxUserService;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

public class WxUserServiceImpl implements WxUserService {

	// 语言，zh_CN 简体(默认)，zh_TW 繁体，en 英语
	@Override
	public WxMpUser wxMpUserFromWx(WxMpService wxMpService, String openid) throws WxErrorException {
		return wxMpService.userInfo(openid, "zh_CN");
	}

	@Override
	public boolean subscribe(WxMpService wxMpService, String openid) throws WxErrorException {
		// WxUser wxUser = WxUser.dao.("update sys_wx_user set where openid=?",
		// wxMpUser.getOpenId());
		int result = Db.update("update sys_wx_user set is_delete=0 where openid=?", openid);
		if (result == 1) {
			return true;
		}
		// 执行插入
		try {
			WxMpUser wxMpUser = wxMpUserFromWx(wxMpService, openid);
			Record record = new Record().setColumns(BeanToMapUtil.convertBean(wxMpUser)).set("is_delete", 0);
			return Db.save("sys_wx_user", record);
		} catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public boolean unSubscribe(String openid) {
		// TODO:执行存储过程
		int result = Db.update("update sys_wx_user set is_delete=1 where openid=?", openid);
		return result > 0;
	}

}
